﻿/***********************************************************************
 * <copyright file="SiteController.cs" company="B/S JSC">
 * -->    Copyright (C) statement. All right reserved
 * </copyright>
 * 
 * Created:   Hoang Bich Son 
 * Email:    sonhb@newman.vn
 * Website:
 * Create Date: Thursday, March 6, 2014
 * Usage: 
 * 
 * RevisionHistory: 
 * Date         Author               Description 
 * 
 * ************************************************************************/

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.Mvc;
using DXWebApplication.Areas.Administrators.Controllers;
using DxMvcApplication.Areas.Administrator.Models;
using DxMvcApplication.Repositories.Core.Security;
using DxMvcApplication.Repositories.Implementations.Security;
using Newtonsoft.Json;

namespace DxMvcApplication.Areas.Administrator.Controllers.Security
{
    /// <summary>
    /// SiteController
    /// </summary>
    public class SiteController : AdminBaseController, IAdminBaseController<SiteModel>
    {
        /// <summary>
        /// The _site repository
        /// </summary>
        private readonly ISiteRepository _siteRepository;

        /// <summary>
        /// Initializes a new instance of the <see cref="SiteController" /> class.
        /// </summary>
        public SiteController()
        {
            _siteRepository = new SiteRepository();
        }
        #region method

        /// <summary>
        /// Inserts this instance.
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public PartialViewResult Insert()
        {
            ViewBag.Parents = GetSites();
            var result = new SiteModel();
            return PartialView("SiteDetail", result);
        }

        /// <summary>
        /// Inserts the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Insert(SiteModel model)
        {
            var msg = string.Empty;
            if (ModelState.IsValid)
            {
                msg = _siteRepository.Insert(model.FromModel());
            }
            return Json(new { message = msg });
        }

        /// <summary>
        /// Updates this instance.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        [HttpGet]
        public PartialViewResult Update(string idJson)
        {
            var idList = JsonConvert.DeserializeObject<List<int>>(idJson);
            var model = new SiteModel();
            if (idList.Count == 1)
            {
                int id;
                int.TryParse(idList[0].ToString(CultureInfo.InvariantCulture), out id);
                if (id > 0)
                {
                    ViewBag.Parents = GetSites();
                    model = _siteRepository.Get(id).ToModel();
                }
            }
            return PartialView("SiteDetail", model);
        }

        /// <summary>
        /// Updates the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Update(SiteModel model)
        {
            var msg = string.Empty;
            if (ModelState.IsValid)
            {                
                msg = _siteRepository.Update(model.FromModel());
            }
            return Json(new { message = msg });
        }

        /// <summary>
        /// Deletes the specified ids.
        /// </summary>
        /// <param name="idJson">The identifier json.</param>
        /// <returns></returns>
        public JsonResult Delete(string idJson)
        {
            string msg;
            try
            {
                var idList = JsonConvert.DeserializeObject<IList<int>>(idJson);
                msg = _siteRepository.Delete(idList);
            }
            catch (Exception)
            {
                return Json(new { message = NmResources.MessageResource.Exception }, JsonRequestBehavior.AllowGet);
            }
            return Json(new { message = msg }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// Gets the paged.
        /// </summary>
        /// <param name="currentPage">The current page.</param>
        /// <returns></returns>
        [HttpGet]
        public PartialViewResult GetPaged(int currentPage = 1)
        {
            var totalPage = 0;
            var result = _siteRepository.GetPaged(ref totalPage, currentPage);
            ViewBag.TotalPage = totalPage;
            ViewBag.CurrentPage = currentPage;
            return PartialView("Site",result.ToModel());
        }

        /// <summary>
        /// Gets the paged.
        /// </summary>
        /// <param name="keyword">The keyword.</param>
        /// <param name="status">The status.</param>
        /// <param name="sort">The sort.</param>
        /// <param name="order">The order.</param>
        /// <param name="totalPage">The total page.</param>
        /// <param name="currentPage">The current page.</param>
        /// <returns></returns>
        [HttpPost]
        public PartialViewResult GetPaged(string keyword = null, bool? status = null, string sort = "", string order = "", int totalPage = 0, int currentPage = 1)
        {            
            var result = _siteRepository.GetAdvancedSearch(keyword, status, sort, order, ref totalPage, currentPage);
            ViewBag.TotalPage = totalPage;
            ViewBag.CurrentPage = currentPage;
            return PartialView("SiteList", result.ToModel());
        }
        #endregion

        #region private
        /// <summary>
        /// Gets the sites.
        /// </summary>
        /// <returns></returns>
        private List<SelectListItem> GetSites()
        {
            var comboboxItems = new List<SelectListItem> { new SelectListItem { Value = "0", Text = NmResources.AdminResource.lbParentDefault } };
            var parents = _siteRepository.GetListByParentId(0);
            foreach (var item in parents)
            {
                comboboxItems.Add(new SelectListItem { Value = item.Id.ToString(CultureInfo.InvariantCulture), Text = item.Title });
                var hasChildren = _siteRepository.GetListByParentId(item.Id);
                if (hasChildren.Count > 0)
                {
                    comboboxItems.AddRange(GetChildrenSite(item.Id, "--"));
                }
            }
            return comboboxItems;
        }

        /// <summary>
        /// Gets the children site.
        /// </summary>
        /// <param name="parentId">The parent identifier.</param>
        /// <param name="sapera">The sapera.</param>
        /// <returns></returns>
        private IEnumerable<SelectListItem> GetChildrenSite(int parentId, string sapera)
        {
            var comboboxItems = new List<SelectListItem>();
            var parents = _siteRepository.GetListByParentId(parentId);
            foreach (var item in parents)
            {
                comboboxItems.Add(new SelectListItem { Value = item.Id.ToString(CultureInfo.InvariantCulture), Text = (sapera + item.Title) });
                var hasChildren = _siteRepository.GetListByParentId(item.Id);
                if (hasChildren.Count <= 0) continue;
                sapera += "--";
                comboboxItems.AddRange(GetChildrenSite(item.Id, sapera));
            }
            return comboboxItems;
        }
        #endregion
    }
}
